//
//  ZTViewController.m
//  练习
//
//  Created by hcios on 2017/7/5.
//  Copyright © 2017年 hcios. All rights reserved.
//


#import "ZTViewController.h"
#import "ZTCollectionViewCell.h"
#import "ZTModel.h"

#import "MJRefresh.h"
#import "AFNetworking.h"
#import "MJRefresh.h"

#import "ZTModel.h"
#import "ZTCollectionViewCell.h"
#import "ZTResultViewController.h"

#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width

@interface ZTViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    NSInteger page;
}

@property (nonatomic,strong) UICollectionView *cardView;

@property (nonatomic,strong) NSMutableArray *dataArr;

@end

static NSString *const CollectionViewCellIdentifier = @"cellID";

@implementation ZTViewController

-(instancetype)init{
    if (self = [super init]) {
        _dataArr = [[NSMutableArray alloc] init];
        page = 1;
    }
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layoutCollectionView];
    
    [self.cardView.mj_header beginRefreshing];
    
}

#pragma mark - 初始化CollectionView
-(void)layoutCollectionView{
    //初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置每个cell的大小
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 210);
    //每个cell之间的距离
    layout.minimumLineSpacing = 10.0f;
    self.cardView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 112) collectionViewLayout:layout];
    self.cardView.delegate = self;
    self.cardView.dataSource = self;
    self.cardView.showsVerticalScrollIndicator = NO;
    //注册cell
    [self.cardView registerClass:[ZTCollectionViewCell class] forCellWithReuseIdentifier:@"cellID"];
    self.cardView.backgroundColor = [UIColor colorWithRed:214 / 255.0f green:226 / 255.0f blue:238 / 255.0f alpha:1.0];
    //刷新
    __weak typeof(self) weakSelf = self;
    
    self.cardView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshGetData:YES];
    }];
    [self.view addSubview:self.cardView];
    
}



-(void)refreshGetData:(BOOL)isRefresh{
    
    isRefresh ? page = 1 : page++;
    NSLog(@"当前页面数量：%ld",(long)page);
    NSString *urlString = @"http://chanyouji.com/api/articles.json";
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@(page) forKey:@"page"];
    
    //网络请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = responseObject;
        if (isRefresh) {
            [_dataArr removeAllObjects];
            self.cardView.mj_footer.state = MJRefreshStateIdle;
        }
        if ([dict count] > 0) {
            for (NSDictionary *dict in responseObject) {
                //取值
                ZTModel *model = [[ZTModel alloc] initWithDict:dict];
                [_dataArr addObject:model];
            }
            if (_dataArr.count < 10) {
                [self.cardView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.cardView reloadData];
            if (!isRefresh && [dict count] == 0) {
                [self.cardView.mj_footer endRefreshingWithNoMoreData];
            }else [self endRefresh];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}


-(void)endRefresh{
    if (page == 1) {
        [self.cardView.mj_header endRefreshing];
    }else [self.cardView.mj_footer endRefreshing];
}




#pragma mark - collectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _dataArr.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZTCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellIdentifier forIndexPath:indexPath];
    cell.cellModel = _dataArr[indexPath.row];
    return cell;
}

#pragma mark - collectionViewDelegate
//设置边距
- (UIEdgeInsets) collectionView:(UICollectionView *)collectionView
                         layout:(UICollectionViewLayout *)collectionViewLayout
         insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 10.0f);
}


//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld%ld",(long)[indexPath section],(long)[indexPath row]);
    ZTResultViewController *VC = [[ZTResultViewController alloc] init];
    ZTModel *model = [[ZTModel alloc] init];
    model = _dataArr[indexPath.row];
    VC.userID = model.selfId;
    VC.backImgUrl = model.image_url;
    VC.nameText = model.name;
    
    [self.navigationController pushViewController:VC animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}

@end
